<template>
  <div class="table-page">
    <CommonTable
        ref="tableRef"
        :columns="tableColumns"
        :config="tableConfig"
        :api="apiConfig"
        @add="handleAdd"
        @edit="handleEdit"
        @selection-change="handleSelectionChange"
    >
      <!-- 自定义头部操作按钮 -->
<!--      <template #header-actions>-->
<!--        <el-button type="primary" @click="handleAdd">-->
<!--          <el-icon><Plus /></el-icon>-->
<!--          新增用户-->
<!--        </el-button>-->
<!--      </template>-->

      <!-- 自定义状态列 -->
      <template #status="{ row }">
        <el-tag :type="row.status === 0 ? 'success' : 'danger'">
          {{ row.status === 0 ? '启用' : '禁用' }}
        </el-tag>
      </template>

      <!-- 自定义性别列 -->
      <template #sex="{ row }">
        <el-tag v-if="row.sex" :type="row.sex === 1 ? 'primary' : 'success'">
          {{ row.sex === 1 ? '男' : '女' }}
        </el-tag>
        <span v-else>-</span>
      </template>

      <!-- 自定义操作列 -->
<!--      <template #actions="{ row }">-->
<!--        <template v-if="row.id!=='1'">-->
<!--          <el-button type="primary" size="small" @click="handleEdit(row)">-->
<!--            编辑-->
<!--          </el-button>-->
<!--          <el-button type="danger" size="small" @click="handleDelete(row)">-->
<!--            删除-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </template>-->
    </CommonTable>

    <!-- 用户表单弹窗 -->
    <CommonForm
        :columnsPerRow="1"
        v-model:visible="showForm"
        :fields="formFields"
        :data="currentUser"
        :title="isEdit ? '编辑用户' : '新增用户'"
        @submit="handleFormSubmit"
        @close="handleFormClose"
    />
  </div>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import CommonTable from '@/components/base/CommonTable/index.vue'
import CommonForm from '@/components/base/CommonForm/index.vue'
import {getApiConfig, getFormFields, getTableColumns, getTableConfig, TableApis} from './index'
import type {UserDetail} from '@/types/user'

// 页面数据
const tableRef = ref()
const formRef = ref()
const isEdit = ref(false)
const currentUser = ref<UserDetail | null>(null)
const showForm = ref(false)
const selectedRows = ref<UserDetail[]>([])

// 表单字段配置
const formFields = computed(() => getFormFields(isEdit.value))

// 表格列配置
const tableColumns = computed(() => getTableColumns())

// 表格配置
const tableConfig = computed(() => getTableConfig())

// API配置
const apiConfig = computed(() => getApiConfig())

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  currentUser.value = null
  showForm.value = true
}

// 编辑用户
const handleEdit = (row: UserDetail) => {
  isEdit.value = true
  currentUser.value = { ...row }
  showForm.value = true
}

const handleDelete = async (row: UserDetail) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除用户 "${row.username}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await TableApis.deleteUser(row.id!)
    ElMessage.success('删除成功')
    tableRef.value?.refresh()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSelectionChange = (selection: UserDetail[]) => {
  selectedRows.value = selection
}

// 表单提交处理
const handleFormSubmit = async (data: UserDetail) => {
  try {
    if (isEdit.value && currentUser.value) {
      // 编辑用户
      await TableApis.updateUser(data)
      ElMessage.success('用户更新成功')
    } else {
      // 新增用户
      await TableApis.createUser(data)
      ElMessage.success('用户创建成功')
    }

    showForm.value = false
    tableRef.value?.refresh()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  }
}

// 表单关闭处理
const handleFormClose = () => {
  showForm.value = false
}
</script>

<style scoped>
.table-page {
  height: 100%;
  background: #f5f5f5;
}
</style>